package cn.com.xy.sms.util;

import java.io.File;
import java.io.InputStream;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.NumberInfo;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;

/* IMOO-9 likuangkuang 20161014 start */
public class EmbedNumberUtils {
	public static final String KEY_DATA_QUERY_VERSION = "version";

	private static final String EMBED_NUMBER_FILE_ZIP_ASSET = "duoqu_embed_number.zip";
	private static final String EMBED_NUMBER_FILE_ZIP = "embed_number.zip";
	private static final String EMBED_NUMBER_FILENAME = "EmbedNumber.txt";
	private static final String OTA_NUMBER_FILE_ZIP = "numberOTA.zip";
	private static final String OTA_NUMBER_FILENAME = "EmbedDiff.txt";
	private static final String KEY_EMBED_NUMBER_VERSION = "embed_number_version";
	private static final String DEFAULT_VERSION = "201606021010";

	private static Context mContext = null;
	private static String mEmbedNumberDir = null;
	private static String mEmbedNumberVersion = null;

	public static void init(final Context context) {
		mContext = context;
		getEmbedNumberVersion();
	}

	public static void setEmbedNumberVersion(String version) {
		if (!StringUtils.isNull(mEmbedNumberVersion) && mEmbedNumberVersion.equals(version)) {
			return;
		}

		mEmbedNumberVersion = version;
		SysParamEntityManager.setParam(KEY_EMBED_NUMBER_VERSION, version);
	}

	public static String getEmbedNumberVersion() {
		if (mEmbedNumberVersion != null) {
			return mEmbedNumberVersion;
		}

		// FIXME what is context for ?
		String version = SysParamEntityManager.getStringParam(mContext, KEY_EMBED_NUMBER_VERSION);
		if (StringUtils.isNull(version)) {
			version = DEFAULT_VERSION;
			setEmbedNumberVersion(version);
		}

		mEmbedNumberVersion = version;
		return mEmbedNumberVersion;
	}

	public static String getEmbedNumberDir() {
		if (!StringUtils.isNull(mEmbedNumberDir)) {
			return mEmbedNumberDir;
		}
		mEmbedNumberDir = Constant.getPath(Constant.DUOQU_EMBED_NUMBER_DIR);
		return mEmbedNumberDir;
	}

	public static void downOTAZipFile(String url) {
		FileUtils.downFile(url, getEmbedNumberDir(), OTA_NUMBER_FILE_ZIP);
	}

	public static String getOTAZipFilePath() {
		return getEmbedNumberDir() + File.separator + OTA_NUMBER_FILE_ZIP;
	}

	private static InputStream getEmbedNumberFileInputStream(String filename) {
		String path = getEmbedNumberDir() + File.separator + filename;
		return FileUtils.getInputStreamFromFile(path);
	}

	public static InputStream unOTANumberZipAndReturnInputStream() throws Exception {
		XyUtil.upZipFile(getOTAZipFilePath(), getEmbedNumberDir());
		return getEmbedNumberFileInputStream(OTA_NUMBER_FILENAME);
	}

	public static InputStream unEmbedNumberZipAndReturnInputStream() throws Exception {
		XyUtil.unZip(Constant.getContext().getResources().getAssets().open(EMBED_NUMBER_FILE_ZIP_ASSET),
				EMBED_NUMBER_FILE_ZIP, getEmbedNumberDir());
		return getEmbedNumberFileInputStream(EMBED_NUMBER_FILENAME);
	}
	
	   /*SDK-639 likuangkuang 20161012 start*/
    /**
     * 处理内嵌数据文件内容获取JSONObject格式号码识别结果
     * 
     * @param resultContainer 存放号码数据的容器，避免new出大量JSONObject，每个号码的数据都放在这个容器中
     * @param numberTagTypeMap 标记号对应标记名称MAP
     * @param res 数据源
     * @param version init:version, upgrade: version online
     * @return
     */
    public static JSONObject handleNumberData(JSONObject resultContainer, Map<String, String> numberTagTypeMap, String res[], String version) {
        // 内嵌数据划分为如下四列:
        // 号码    类别(企业号码或者标记号码)    标记类型/企业Logo    标记数/企业名称    数据来源
        // 说明：
        // res[0]:号码
        // res[1]:1:代表该号码为企业号码   2:该号码为标记号码
        // res[2]:当为标记号码的时候该项为标记的类型；当为企业号码的时候该项为企业的Logo信息
        // res[3]:当为标记号码的时候该项为标记数；当为企业号码的时候该项为企业名称
        // res[4]:当为1的时候代表认证数据；当为0的时候代表非认证数据
        // res[5]:该数据的来源 0代表联盟
        // 样例：
        // 114118   1   6b7d6f1f8abb0c5e0c2260521edb1bb6.png    中国电信号码百事通   0   0
        // 02431025600  2   1   1753    0   0
        /* IMOO-9 likuangkuang 20161014 start */
        if (res == null || res.length < 6) {
        /* IMOO-9 likuangkuang 20161014 end */
            
            return null;
        }
        try {
            resultContainer.put(NumberInfo.NUM_KEY, res[0]);
            String type = res[1];
            if ("1".equals(type)) {
                // 企业号码
                resultContainer.remove(NumberInfo.TYPE_KEY);
                resultContainer.remove(NumberInfo.TAG_KEY);
                resultContainer.remove(NumberInfo.AMOUNT_KEY);
                resultContainer.put(NumberInfo.NUM_TYPE_KEY, 1); // 1代表为企业号码
                String logo = res[2];
                resultContainer.put(NumberInfo.LOGO_KEY, StringUtils.isNull(logo) ? "" : logo);
                resultContainer.put(NumberInfo.NAME_KEY, res[3]);
            } else {
                // 标记号码
                resultContainer.remove(NumberInfo.NUM_TYPE_KEY);
                resultContainer.remove(NumberInfo.LOGO_KEY);
                resultContainer.remove(NumberInfo.NAME_KEY);
                resultContainer.put(NumberInfo.TYPE_KEY, 2); // 2代表为标记号码
                String tag = numberTagTypeMap.get(res[2]);
                resultContainer.put(NumberInfo.TAG_KEY,  StringUtils.isNull(tag) ? "" : tag);
                resultContainer.put(NumberInfo.AMOUNT_KEY, Integer.parseInt(res[3]));
            }
            resultContainer.put(NumberInfo.AUTH_KEY, "1".equals(res[4]) ? 1 : 0); // auth为1代表是认证数据，为0代表非认证数据
            resultContainer.put(NumberInfo.SOURCE_KEY, Integer.parseInt(res[5]));
            resultContainer.put(NumberInfo.VERSION_KEY, version);
            return resultContainer;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG,
                    "EmbedNumberUtils handleNumberData error:", e);
        }
        return null;
    }
    /*SDK-639 likuangkuang 20161012 end*/

}
/* IMOO-9 likuangkuang 20161014 end */